/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package operators;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

/**
 *
 * @author Dragan
 */
public class OperationsHolder<T extends Operation> implements Iterable<T> {

    private List<List<T>> list;

    public OperationsHolder() {
        list = new ArrayList<List<T>>();
    }

    public void add(T operation) {
        list.add(new ArrayList<T>(Arrays.asList(operation)));
    }

    public void addAll(List<T> operations) {
        for (T operation : operations) {
            list.add(new ArrayList<T>(Arrays.asList(operation)));
        }
    }

    public void addParallelToPrevious(T operation) {
        list.get(list.size() - 1).add(operation);
    }

    public void addAllParallel(List<T> operations) {
        list.add(operations);
    }

    public void addAll(OperationsHolder<T> operations) {
        list.addAll(operations.list);
    }

    public Operation get(int i) {
        return list.get(i).get(0);
    }

    public int size() {
        return list.size();
    }

    public Iterator<T> iterator() {
        List<T> operations = new ArrayList<T>();
        for (List<T> sublist : list) {
            operations.addAll(sublist);
        }
        return operations.iterator();
    }

    public void clear() {
        this.list.clear();
    }

    public String getShortDesc() {
        String str = "";
        for (List<T> sublist : list) {
            for (T operation : sublist) {
                str += operation + ",\n";
            }
        }
        return str;
    }

    @Override
    public String toString() {
        StringBuffer sb = new StringBuffer();
        String space = "";
        List<List<T>> reverseList = new ArrayList<List<T>>();
        for (List<T> sublist : list) {
            reverseList.add(0, sublist);
        }
        for (List<T> sublist : reverseList) {
            for (T operation : sublist) {
                sb.append(operation + "\n" + space);
            }
            space += "  ";
        }
        return sb.toString();
    }
}
